//
//  Category.m
//  Core
//
//  Created by Cuong Doan on 3/5/13.
//  Copyright (c) 2013 Cuong Doan. All rights reserved.
//

#import "Category.h"

@interface Category ()

-(void)getCatByID:(int)catID;

@end

@implementation Category
{
    sqlite3 *db;
}

@synthesize CatID, CatName, Description;

-(id)initWithID:(int)catID
{
    self = [super init];   
    
    @try
    {
        [self getCatByID:catID];
    }
    @catch (NSException *exception)
    {
        @throw exception;
    }
    
    return self;
}

-(void)getCatByID:(int)catID
{
    sqlite3_stmt *statement;
    
    const char *sql = "select * from FlowCategory where Cat_ID = ?";    
        
    @try
    {       
        [DatabaseManager openAndPrepareDatabase:&db andStatement:&statement andSQL:sql];
        
        [DatabaseManager bindInt:statement andValue:catID andIndex:1];
        
        while(sqlite3_step(statement) == SQLITE_ROW)
        {
            self.CatID = sqlite3_column_int(statement, 0);
            
            self.CatName = [NSString stringWithUTF8String:(char *)sqlite3_column_text(statement, 1)];
            
            self.Description = [NSString stringWithUTF8String:(char *)sqlite3_column_text(statement, 2)];
        }
    }
    @catch (NSException *exception)
    {
        @throw exception;
    }
    @finally
    {
        sqlite3_close(db);
    }
}

-(void)insertCategory
{
    sqlite3_stmt *statement;
    
    const char *sql = "insert into FlowCategory (Cat_Name, Description) values (?, ?)";    
        
    @try
    {
        [DatabaseManager openAndPrepareDatabaseV2:&db andStatement:&statement andSQL:sql];
        
        [DatabaseManager bindText:statement andValue:self.CatName andIndex:1];
        
        [DatabaseManager bindText:statement andValue:self.Description andIndex:2];
        
        sqlite3_step(statement);
        
        sqlite3_finalize(statement);
    }
    @catch (NSException *exception)
    {
        @throw exception;
    }
    @finally
    {
        sqlite3_close(db);
    }
}

-(void)updateCategory
{
    sqlite3_stmt *statement;
    
    const char *sql = "update FlowCategory set Cat_Name = ?, Description = ? where Cat_ID = ?";    
        
    @try
    {
        [DatabaseManager openAndPrepareDatabaseV2:&db andStatement:&statement andSQL:sql];
        
        [DatabaseManager bindText:statement andValue:self.CatName andIndex:1];

        [DatabaseManager bindText:statement andValue:self.Description andIndex:2];
        
        [DatabaseManager bindInt:statement andValue:self.CatID andIndex:3];
        
        sqlite3_step(statement);
        
        sqlite3_finalize(statement);
    }
    @catch (NSException *exception)
    {
        @throw exception;
    }
    @finally
    {
        sqlite3_close(db);
    }
}

@end
